package com.focusai.efairy.ui.presenter;

import android.text.TextUtils;

import com.focusai.efairy.model.ResultInfo;
import com.focusai.efairy.model.manager.CacheManager;
import com.focusai.efairy.model.request.CheckCodeRequest;
import com.focusai.efairy.model.request.LoginRequest;
import com.focusai.efairy.model.request.PasswdLoginRequest;
import com.focusai.efairy.model.response.LoginResponse;
import com.focusai.efairy.network.HttpManager;
import com.focusai.efairy.network.Response;
import com.focusai.efairy.network.exception.NetworkException;
import com.focusai.efairy.network.exception.ServerException;
import com.focusai.efairy.ui.Ipresenter.ILoginPresenter;
import com.focusai.efairy.ui.iview.ILogin;
import com.focusai.efairy.utils.Base64Utils;
import com.focusai.efairy.utils.ErrorCodeUtils;
import com.focusai.efairy.utils.JiGuangPushUtil;
import com.focusai.efairy.utils.StringUtils;
import com.focusai.efairy.utils.log.Log;

import io.rong.imlib.RongIMClient;

/**
 * Created by Luogw on 2017/7/26.
 */

public class LoginPresenter implements ILoginPresenter {
    private static final String TAG = LoginPresenter.class.getName();
    private ILogin mLogin;

    public LoginPresenter(ILogin mLogin) {
        this.mLogin = mLogin;
    }

    @Override
    public void login(final String phone, String code) {
        HttpManager.getInstance().sendRequest(new LoginRequest(phone, code, new Response.Listener<ResultInfo<LoginResponse>>() {
            @Override
            protected void onSuccess(ResultInfo<LoginResponse> response) {
                if (response != null && response.result != null) {
                    if (mLogin != null) {
                        if (response.err_code == 200) {
                            CacheManager.saveLoginInfo(response.result, phone);
                            connectToRoogYun(response.result.rongcloud_token);
                        } else {
                            mLogin.loginFinish(false, "", TextUtils.isEmpty(response.msg) ?
                                    ErrorCodeUtils.getErrorMsgByCode(response.err_code) : Base64Utils.decodeStr(response.msg));
                        }
                    }
                } else if (response != null && !TextUtils.isEmpty(response.msg)) {
                    mLogin.loginFinish(false, "", response.msg);
                } else {
                    mLogin.loginFinish(false, "", "登录失败");
                }
            }

            @Override
            protected void onFail(NetworkException exception) {
                if (exception != null) {
                    Log.D(TAG, exception.getErrorMessage());
                    if (exception instanceof ServerException) {
                        mLogin.loginFinish(false, "", ((ServerException) exception).getErrorMessage());
                    } else {
                        mLogin.loginFinish(false, "", exception.getErrorMessage());
                    }
                }
            }
        }));
    }

    @Override
    public void loginUsePasswd(final String phone, final String passwd) {
        HttpManager.getInstance().sendRequest(new PasswdLoginRequest(phone, passwd, new Response.Listener<ResultInfo<LoginResponse>>() {
            @Override
            protected void onSuccess(ResultInfo<LoginResponse> response) {
                if (response != null && response.result != null) {
                    if (mLogin != null) {
                        if (response.err_code == 200) {
                            CacheManager.saveLoginInfo(response.result, phone);
                            connectToRoogYun(response.result.rongcloud_token);
                        } else {
                            mLogin.loginFinish(false, "", TextUtils.isEmpty(response.msg) ?
                                    ErrorCodeUtils.getErrorMsgByCode(response.err_code) : Base64Utils.decodeStr(response.msg));
                        }
                    }
                } else if (response != null && !TextUtils.isEmpty(response.msg)) {
                    mLogin.loginFinish(false, "", response.msg);
                } else {
                    mLogin.loginFinish(false, "", "登录失败");
                }
            }

            @Override
            protected void onFail(NetworkException exception) {
                if (exception != null) {
                    Log.D(TAG, exception.getErrorMessage());
                    if (exception instanceof ServerException) {
                        mLogin.loginFinish(false, "", ((ServerException) exception).getErrorMessage());
                    } else {
                        mLogin.loginFinish(false, "", exception.getErrorMessage());
                    }
                }
            }
        }));
    }

    @Override
    public void getCheckCode(String phone) {
        HttpManager.getInstance().sendRequest(new CheckCodeRequest(phone, new Response.Listener<String>() {
            @Override
            protected void onSuccess(String response) {
                if (response != null && !TextUtils.isEmpty(response)) {
                    mLogin.getCodeFinish(true, "", null);
                }
            }

            @Override
            protected void onFail(NetworkException exception) {
                if (exception instanceof ServerException) {
                    String errorMessage = ((ServerException) exception).getErrorMessage();
                    mLogin.getCodeFinish(false, "", StringUtils.isStickBlank(errorMessage) ?
                            ErrorCodeUtils.getErrorMsgByCode(((ServerException) exception).getErrorCode()) : errorMessage);
                } else {
                    mLogin.getCodeFinish(false, "", exception.getErrorMessage());
                }
            }
        }));
    }

    private void connectToRoogYun(String token) {
        RongIMClient.connect(token, new RongIMClient.ConnectCallback() {

            /**
             * Token 错误。可以从下面两点检查 1.  Token 是否过期，如果过期您需要向 App Server 重新请求一个新的 Token
             *                            2.  token 对应的 appKey 和工程里设置的 appKey 是否一致
             */
            @Override
            public void onTokenIncorrect() {
                Log.D(TAG, "融云登录onTokenIncorrect");
                if (mLogin != null) {
                    mLogin.loginFinish(false, "", "融云登录token无效");
                }
            }

            /**
             * 连接融云成功
             * @param userid 当前 token 对应的用户 id
             */
            @Override
            public void onSuccess(String userid) {
                Log.D(TAG, "融云登录成功 用户Userid = " + userid);
                if (mLogin != null) {
                    Log.D(TAG, "极光推送设置别名 = " + userid);
                    JiGuangPushUtil.setAlias(1, userid);
                    mLogin.loginFinish(true, "", "");
                }
            }

            /**
             * 连接融云失败
             * @param errorCode 错误码，可到官网 查看错误码对应的注释
             */
            @Override
            public void onError(RongIMClient.ErrorCode errorCode) {
                Log.D(TAG, "融云登录失败 errorCode = " + errorCode);
                if (mLogin != null) {
                    mLogin.loginFinish(false, "", "融云登录失败");
                }
            }
        });
    }

}
